<!-- eslint-disable no-console -->
<script lang="ts" setup>
import type { DictApi } from '#/api';
import type { workstationAPI } from '#/api/mes/md/workstation';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { DictResp } from '#/api';
import { addWorkstation, updateWorkstation } from '#/api/mes/md/workstation';
import { baseRequestClient } from '#/api/request';

const emit = defineEmits(['success']);
const formdata = ref<workstationAPI.Row>();
const sys_yes_no = reactive<DictApi.SelectOption[]>([]);
// const mes_mainten_type = reactive<DictApi.SelectOption[]>([]);

DictResp(['sys_yes_no', 'mes_client_type']).then((res) => {
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});

// 自动生成编码
const getAutoCode = () =>
  baseRequestClient.get<any>('/system/autocode/get/WORKSTATION_CODE');

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // wrapperClass: 'grid-cols-2',
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      rules: 'required',
      fieldName: 'workstationCode',
      formItemClass: 'w-[300px] ml-[-20px]',
      label: '工作站编码',
      componentProps: { placeholder: '请输入工作站编码' },
    },
    {
      component: 'Switch',
      fieldName: 'switch',
      formItemClass: 'w-[160px] mt-[-58px] ml-[260px]',
      label: '自动生成',
      componentProps: {
        onChange: async (e: boolean) => {
          if (e) {
            const res = await getAutoCode();
            baseFormApi.setFieldValue('workstationCode', res.data); // 直接更新
          } else {
            baseFormApi.setFieldValue('workstationCode', '');
          }
        },
      },
    },

    {
      component: 'Input',
      rules: 'required',
      formItemClass: 'w-[420px] ml-[-20px]',
      componentProps: {
        placeholder: '请输入工作站名称',
      },
      fieldName: 'workstationName',
      label: '工作站名称',
    },
    {
      component: 'InputNumber',
      fieldName: 'area',
      formItemClass: 'w-[420px] ml-[-20px]',
      label: '面积',
      componentProps: {
        min: 0,
        defaultValue: 0,
        controls: true,
        class: 'w-full',
      },
    },
    {
      component: 'Input',
      formItemClass: 'w-[420px] ml-[-20px]',
      componentProps: {
        placeholder: '请输入负责人',
      },
      fieldName: 'charge',
      label: '负责人',
    },

    {
      component: 'RadioGroup',
      rules: 'required',
      componentProps: {
        allowClear: true,
        options: sys_yes_no,
        placeholder: '是否启用',
      },
      fieldName: 'enableFlag',
      label: '是否启用',
    },
    {
      component: 'Input',
      formItemClass: ' ml-[-20px]',
      componentProps: {
        placeholder: '',
        class: 'h-[80px]',
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
  // wrapperClass: 'grid-cols-1',
});

const [Modal, modalApi] = useVbenModal({
  showConfirmButton: true,
  showCancelButton: true,
  closeOnClickModal: false,
  async onConfirm() {
    const { valid } = await baseFormApi.validate();
    if (valid) {
      modalApi.lock();
      let data;
      await baseFormApi.getValues().then((res) => {
        console.log('Form Data:', res); // 打印表单数据以确认字段
        data = res;
      });
      try {
        await (formdata.value?.workstationId
          ? updateWorkstation(data!) // 修改
          : addWorkstation(data!)); // 新增

        modalApi.close();
        emit('success');
      } catch (error) {
        console.error('Error:', error);
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData();
      if (data) {
        formdata.value = data.row;
        console.log('Modal Data:', formdata.value); // 打印数据以确认
        baseFormApi.setValues(formdata.value as any);
      }
    }
  },
});

function onSubmit(values: Record<string, any>) {
  console.log(values);

  modalApi.close();
}
</script>

<template>
  <Modal>
    <BaseForm />
  </Modal>
</template>
